﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
//using System.Threading;
using Microsoft.Office.Interop.Excel;
using EXCEL = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.CSharp.RuntimeBinder;
using System.IO;

namespace uart_excel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            ttt.Interval = 100;
            ttt.Tick += timerttt_Tick;
            ttt.Enabled = true;

            port.DataReceived += serialPort1_DataReceived22;
            port.NewLine = "\r\n";
            //port.Encoding = Encoding.ASCII;
            port.Parity = Parity.None;
            port.StopBits = StopBits.One;

            read_lines();
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string[]  aaa = SerialPort.GetPortNames();
            //foreach(var a in aaa)
            index = 0;
            if (button1.Text != "关闭")
            {
                port.PortName = textBox1.Text;
                port.BaudRate = Convert.ToInt32(textBox2.Text);
                try
                {
                    if (port.IsOpen == false)
                        port.Open();

                    if (port.IsOpen)
                    {
                        label1.Text = "已打开" + textBox1.Text;
                        button1.Text = "关闭";
                    }
                    else
                        label1.Text = "打开失败";
                }
                catch
                {
                    port.Close();
                    label1.Text = "打开失败";
                }
            }
            else
            {
                try
                {
                    if (port.IsOpen)
                        port.Close();

                    if (port.IsOpen)
                    {
                        button1.Text = "打开串口";
                        label1.Text = "已关闭";
                    }
                    else
                        label1.Text = "关闭失败";
                }
                catch
                {
                    label1.Text = "关闭失败";
                }
            }
        }
        //public delegate void mydelegate(string delestr);
        //public void click(string str)
        //{        //    
        //    textBox3.Text = str;
        //}
        SerialPort port = new SerialPort(); //串口

        private void serialPort1_DataReceived22(object sender, SerialDataReceivedEventArgs e)
        {

        }

        byte[] received_buf = new byte[100];
        byte[] rn = { 13, 10, 0, 77 };  //芯片IDE编译的换行符"\r\n"与C#不同
        Timer ttt = new Timer();//每100毫秒取数据
        private void timerttt_Tick(object sender, EventArgs e)
        {
            if (port.IsOpen == false)
                return;
            int toRead = port.BytesToRead;
            if (toRead <= 0)
                return;
            if (toRead > 19)
            {
                port.ReadExisting();
                return;
            }
            //读缓存
            for (int i = 0; i < toRead; i++)
            {
                received_buf[i] = Convert.ToByte(port.ReadByte());
            }
            //取换行符
            byte[] jw = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                jw[i] = received_buf[toRead - 4 + i];
            }
            if (Convert.ToString(jw) == Convert.ToString(rn))//如果结尾等于"\r\n"
            {
                toRead -= 4;
                //心跳包
                byte[] xtb = new byte[6];
                for (int i = 0; i < 6; i++)
                {
                    xtb[i] = received_buf[i + 1];
                }
                if (Encoding.Default.GetString(xtb) == "心跳包")
                {
                    int VOL = received_buf[7] * 256 + received_buf[8];//电池电压
                    //int VIN = received_buf[9] * 256 + received_buf[10];
                    int SOC_FLAG = received_buf[9];
                    int VIN_FLAG = received_buf[10];
                    int BAT_PS = received_buf[11];//电池百分比
                    int SHOW_PS = received_buf[12];//充放电闲置换算电压百分比
                    int Level = received_buf[13];
                    int LED_ST = received_buf[14];   //灯
                    string www = VOL + "\t" + BAT_PS + "\t" + SHOW_PS + "\t" + Level + "\t" + SOC_FLAG + "\t" + VIN_FLAG + "\t" + LED_ST;
                    //Console.WriteLine(www);
                    show_data(www);
                }
            }
        }

        /// <summary>
        /// 序号
        /// </summary>
        int index = 0;
        /// <summary>
        /// 显示数据
        /// </summary>
        /// <param name="data">收到的数据</param>
        void show_data(string data)
        {
            DateTime tt = DateTime.Now;
            string aa = index++.ToString() + '\t' + tt.ToString("T") + "." + tt.Millisecond.ToString() + '\t' + data;

            int lines = textBox3.Lines.Count();
            string showshow = "";
            int start = 0;
            if (lines >= 20)        //只显示20行
                start = 1;
            for (int i = start; i < lines; i++)
            {
                showshow += textBox3.Lines[i] + "\r\n"; //加上电脑时间
            }
            textBox3.Text = showshow + aa;

            if (is_save)
                save_data(aa);
        }

        string path = System.IO.Directory.GetCurrentDirectory();//获取应用程序的当前工作目录
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="data"></param>        
        void save_data(string data)
        {
            try
            {
                StreamWriter sw = new StreamWriter(path + @"\采集.txt", true);//true为追加到文件尾
                sw.WriteLine(data);
                sw.Close();
            }
            catch
            { }
            lines++;    //放这，丢帧可在TXT里发现
            label2.Text = "数据行数：" + lines.ToString();
        }
        bool is_save = false;
        private void button2_Click(object sender, EventArgs e)
        {
            index = 0;
            if (MessageBox.Show("确认要删除记录数据?", "确认删除", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    StreamWriter sw = new StreamWriter(path + @"\采集.txt");//true为追加到文件尾
                    sw.WriteLine("序号\t时间\t电压\t电池百分比\tSHOW百分比\tLevel\tSOC\tVIN\tLED");
                    sw.Close();
                }
                catch
                {
                    MessageBox.Show("删除失败，可能被占用");
                }
                read_lines();

            }
        }

        int lines = 0;//记录的总行数
        private void button3_Click(object sender, EventArgs e)
        {
            index = 0;
            if (is_save)
            {
                is_save = false;
                button3.Text = "开始记录";
            }
            else
            {
                is_save = true;
                button3.Text = "停止记录";
                read_lines();
            }
        }
        void read_lines()
        {
            lines = 0;
            try
            {
                StreamReader sr = new StreamReader(path + @"\采集.txt");
                while (sr.ReadLine() != null)
                {
                    lines++;
                }
                sr.Close();
                lines -= 1;//不记标题
                label2.Text = "数据行数：" + lines.ToString();
            }
            catch
            {
                label2.Text = "采集.txt 不存在或被占用，可尝试清空";
            }

        }
    }
}